// 全局变量
let allDocuments = [];
let filteredDocuments = [];
let currentDeleteId = null;

// DOM元素
const totalDocsEl = document.getElementById('totalDocs');
const totalViewsEl = document.getElementById('totalViews');
const avgViewsEl = document.getElementById('avgViews');
const totalSizeEl = document.getElementById('totalSize');
const documentsLoading = document.getElementById('documentsLoading');
const documentsTable = document.getElementById('documentsTable');
const documentsTableBody = document.getElementById('documentsTableBody');
const emptyState = document.getElementById('emptyState');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const sortSelect = document.getElementById('sortSelect');
const refreshBtn = document.getElementById('refreshBtn');
const logoutBtn = document.getElementById('logoutBtn');
const userInfo = document.getElementById('userInfo');
const usernameSpan = document.getElementById('username');
const deleteModal = document.getElementById('deleteModal');
const detailModal = document.getElementById('detailModal');
const deleteDocName = document.getElementById('deleteDocName');
const documentDetail = document.getElementById('documentDetail');
const notification = document.getElementById('notification');

// 按钮元素
const closeDeleteModal = document.getElementById('closeDeleteModal');
const closeDetailModal = document.getElementById('closeDetailModal');
const cancelDelete = document.getElementById('cancelDelete');
const confirmDelete = document.getElementById('confirmDelete');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    checkAuthStatus();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 刷新按钮
    refreshBtn.addEventListener('click', loadDocuments);
    
    // 登出按钮
    logoutBtn.addEventListener('click', handleLogout);
    
    // 搜索功能
    searchInput.addEventListener('input', handleSearch);
    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    });
    
    // 排序功能
    sortSelect.addEventListener('change', handleSort);
    
    // 删除模态框
    closeDeleteModal.addEventListener('click', closeDeleteModalFunc);
    cancelDelete.addEventListener('click', closeDeleteModalFunc);
    confirmDelete.addEventListener('click', handleDeleteConfirm);
    
    // 详情模态框
    closeDetailModal.addEventListener('click', closeDetailModalFunc);
    
    // 模态框外部点击关闭
    deleteModal.addEventListener('click', (e) => {
        if (e.target === deleteModal) {
            closeDeleteModalFunc();
        }
    });
    
    detailModal.addEventListener('click', (e) => {
        if (e.target === detailModal) {
            closeDetailModalFunc();
        }
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', handleKeyboardShortcuts);
}

// 检查登录状态
async function checkAuthStatus() {
    try {
        const response = await fetch('/api/auth/status');
        const data = await response.json();
        
        if (!data.authenticated) {
            // 未登录，重定向到登录页面
            window.location.href = '/login';
            return;
        }
        
        // 显示用户信息
        usernameSpan.textContent = data.username;
        userInfo.style.display = 'flex';
        
        // 加载文档列表
        loadDocuments();
    } catch (error) {
        console.error('检查登录状态失败:', error);
        window.location.href = '/login';
    }
}

// 处理登出
async function handleLogout() {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            showNotification('登出成功', 'success');
            setTimeout(() => {
                window.location.href = '/login';
            }, 1000);
        } else {
            throw new Error('登出失败');
        }
    } catch (error) {
        console.error('登出错误:', error);
        showNotification('登出失败，请稍后重试', 'error');
    }
}

// 加载文档列表
async function loadDocuments() {
    try {
        showLoading(true);
        
        const response = await fetch('/api/documents');
        
        if (response.status === 401) {
            // 未授权，重定向到登录页面
            window.location.href = '/login';
            return;
        }
        
        if (!response.ok) {
            throw new Error('获取文档列表失败');
        }
        
        const documents = await response.json();
        allDocuments = documents;
        filteredDocuments = [...documents];
        
        updateStatistics(documents);
        displayDocuments(documents);
        
        showLoading(false);
        
    } catch (error) {
        console.error('加载文档失败:', error);
        showNotification('加载文档列表失败', 'error');
        showLoading(false);
    }
}

// 显示/隐藏加载状态
function showLoading(show) {
    if (show) {
        documentsLoading.style.display = 'flex';
        documentsTable.style.display = 'none';
        emptyState.style.display = 'none';
    } else {
        documentsLoading.style.display = 'none';
    }
}

// 更新统计信息
function updateStatistics(documents) {
    const totalDocs = documents.length;
    const totalViews = documents.reduce((sum, doc) => sum + (doc.views || 0), 0);
    const avgViews = totalDocs > 0 ? Math.round(totalViews / totalDocs) : 0;
    const totalSize = documents.reduce((sum, doc) => sum + (doc.size || 0), 0);
    
    totalDocsEl.textContent = totalDocs;
    totalViewsEl.textContent = totalViews.toLocaleString();
    avgViewsEl.textContent = avgViews;
    totalSizeEl.textContent = formatFileSize(totalSize);
}

// 显示文档列表
function displayDocuments(documents) {
    if (documents.length === 0) {
        documentsTable.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }
    
    documentsTable.style.display = 'block';
    emptyState.style.display = 'none';
    
    documentsTableBody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = createDocumentRow(doc);
        documentsTableBody.appendChild(row);
    });
}

// 创建文档行
function createDocumentRow(doc) {
    const row = document.createElement('div');
    row.className = 'document-row';
    
    const uploadTime = new Date(doc.uploadTime).toLocaleString('zh-CN');
    const lastViewed = doc.lastViewed 
        ? new Date(doc.lastViewed).toLocaleString('zh-CN')
        : '从未访问';
    
    row.innerHTML = `
        <div class="doc-name" onclick="showDocumentDetail('${doc.id}')">
            ${doc.originalName}
        </div>
        <div class="doc-size">${formatFileSize(doc.size)}</div>
        <div class="doc-upload-time">${uploadTime}</div>
        <div class="doc-views">${doc.views || 0}</div>
        <div class="doc-last-viewed">${lastViewed}</div>
        <div class="doc-actions">
            <a href="/share/${doc.id}" target="_blank" class="action-btn-small view-btn">
                👁️ 查看
            </a>
            <a href="/api/export/html/${doc.id}" class="action-btn-small export-btn">
                📄 导出
            </a>
            <button onclick="showDeleteModal('${doc.id}', '${doc.originalName}')" class="action-btn-small delete-btn">
                🗑️ 删除
            </button>
        </div>
    `;
    
    return row;
}

// 搜索处理
function handleSearch() {
    const query = searchInput.value.toLowerCase().trim();
    
    if (query === '') {
        filteredDocuments = [...allDocuments];
    } else {
        filteredDocuments = allDocuments.filter(doc => 
            doc.originalName.toLowerCase().includes(query)
        );
    }
    
    handleSort(); // 应用当前排序
}

// 排序处理
function handleSort() {
    const sortBy = sortSelect.value;
    
    filteredDocuments.sort((a, b) => {
        switch (sortBy) {
            case 'uploadTime':
                return new Date(b.uploadTime) - new Date(a.uploadTime);
            case 'views':
                return (b.views || 0) - (a.views || 0);
            case 'size':
                return (b.size || 0) - (a.size || 0);
            case 'name':
                return a.originalName.localeCompare(b.originalName);
            default:
                return 0;
        }
    });
    
    displayDocuments(filteredDocuments);
}

// 显示文档详情
function showDocumentDetail(docId) {
    const doc = allDocuments.find(d => d.id === docId);
    if (!doc) return;
    
    const uploadTime = new Date(doc.uploadTime).toLocaleString('zh-CN');
    const lastViewed = doc.lastViewed 
        ? new Date(doc.lastViewed).toLocaleString('zh-CN')
        : '从未访问';
    
    const shareUrl = `${window.location.origin}/share/${doc.id}`;
    
    documentDetail.innerHTML = `
        <div class="detail-grid">
            <div class="detail-item">
                <span class="detail-label">📄 文档名称:</span>
                <span class="detail-value">${doc.originalName}</span>
            </div>
            <div class="detail-item">
                <span class="detail-label">📊 文件大小:</span>
                <span class="detail-value">${formatFileSize(doc.size)}</span>
            </div>
            <div class="detail-item">
                <span class="detail-label">📅 上传时间:</span>
                <span class="detail-value">${uploadTime}</span>
            </div>
            <div class="detail-item">
                <span class="detail-label">👁️ 访问次数:</span>
                <span class="detail-value">${doc.views || 0}</span>
            </div>
            <div class="detail-item">
                <span class="detail-label">🕒 最后访问:</span>
                <span class="detail-value">${lastViewed}</span>
            </div>
            <div class="detail-item">
                <span class="detail-label">🔗 分享链接:</span>
                <span class="detail-value">
                    <div class="share-url">${shareUrl}</div>
                </span>
            </div>
            <div class="detail-item">
                <span class="detail-label">🆔 文档ID:</span>
                <span class="detail-value">${doc.id}</span>
            </div>
        </div>
        
        <div style="margin-top: 20px; text-align: center;">
            <a href="/share/${doc.id}" target="_blank" class="action-btn-small view-btn" style="margin-right: 10px;">
                👁️ 查看文档
            </a>
            <a href="/api/export/html/${doc.id}" class="action-btn-small export-btn">
                📄 导出HTML
            </a>
        </div>
    `;
    
    detailModal.classList.add('show');
}

// 显示删除确认模态框
function showDeleteModal(docId, docName) {
    currentDeleteId = docId;
    deleteDocName.textContent = docName;
    deleteModal.classList.add('show');
}

// 关闭删除模态框
function closeDeleteModalFunc() {
    deleteModal.classList.remove('show');
    currentDeleteId = null;
}

// 关闭详情模态框
function closeDetailModalFunc() {
    detailModal.classList.remove('show');
}

// 确认删除
async function handleDeleteConfirm() {
    if (!currentDeleteId) return;
    
    try {
        const response = await fetch(`/api/document/${currentDeleteId}`, {
            method: 'DELETE'
        });
        
        if (response.status === 401) {
            // 未授权，重定向到登录页面
            window.location.href = '/login';
            return;
        }
        
        if (!response.ok) {
            throw new Error('删除失败');
        }
        
        const result = await response.json();
        
        showNotification('文档删除成功', 'success');
        closeDeleteModalFunc();
        
        // 重新加载文档列表
        loadDocuments();
        
    } catch (error) {
        console.error('删除文档失败:', error);
        showNotification('删除文档失败', 'error');
    }
}

// 键盘快捷键
function handleKeyboardShortcuts(e) {
    // Ctrl/Cmd + F: 聚焦搜索框
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        searchInput.focus();
    }
    
    // F5 或 Ctrl/Cmd + R: 刷新
    if (e.key === 'F5' || ((e.ctrlKey || e.metaKey) && e.key === 'r')) {
        e.preventDefault();
        loadDocuments();
    }
    
    // Escape: 关闭模态框
    if (e.key === 'Escape') {
        closeDeleteModalFunc();
        closeDetailModalFunc();
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 优化搜索性能
const debouncedSearch = debounce(handleSearch, 300);
searchInput.removeEventListener('input', handleSearch);
searchInput.addEventListener('input', debouncedSearch);

// 全局函数（供HTML调用）
window.showDocumentDetail = showDocumentDetail;
window.showDeleteModal = showDeleteModal;

// 错误处理
window.addEventListener('error', (event) => {
    console.error('页面错误:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    event.preventDefault();
});

// 页面可见性变化时刷新数据
document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
        loadDocuments();
    }
});